import { Button } from '@sei/suid-mobile';
import {
  AddCircleOutline,
  ArrowsAltOutline,
  EyeOutline,
  ShrinkOutline,
} from '@sei/suid-mobile-icons';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import LayoutCard from '../../layout/Card';
import { getFormat } from '../utils';
import './index.less';

// 首字母转大写
const strToUpperCase = (str: string) => {
  if (!str) {
    return '';
  }
  return str.charAt(0).toUpperCase() + str.slice(1);
};

const findLabels = (value: any[], options: any[]) => {
  if (
    !Array.isArray(value) ||
    !Array.isArray(options) ||
    value.length === 0 ||
    options.length === 0
  )
    return [];

  return value.map((v) => options.find((o) => o.value === v)?.label);
};

const flatCascaderOptions = (options: any[]) => {
  const result = [];

  const walk = (list: any[]) => {
    list.forEach((i) => {
      result.push(i);
      if (Array.isArray(i.children) && i.children.length > 0) {
        walk(i.children);
      }
    });
  };

  walk(options);
  return result;
};

const isValidateArray = (list: unknown) =>
  Array.isArray(list) && list.length > 0;

const getValueByWidgetType = (value: any, schema: any) => {
  // 获取组件属性，包括options等
  const props = schema.props || {};
  const options = props.options || [];

  const widget = strToUpperCase(schema.widget);
  let result: string;

  switch (widget) {
    case 'Input':
    case 'TextArea':
    case 'Rate':
    case 'Stepper':
      result = value;
      break;
    case 'Slider':
      if (isValidateArray(value)) {
        result = value.join('-');
      } else {
        result = value;
      }
      break;
    case 'Selector':
      if (isValidateArray(value)) {
        result = findLabels(value, options).join('，');
      } else {
        result = value;
      }
      break;
    case 'Switch':
      {
        const { uncheckedText = '否', checkedText = '是' } = props;
        result = value ? checkedText : uncheckedText;
      }
      break;
    case 'Radio':
      result = options.find((o: any) => o.value === value)?.label || value;
      break;
    case 'DatePicker':
      {
        const { format, precision } = props;
        if (!value) return '-';
        const dateFormat = format || getFormat(precision);
        result = dayjs(value).format(dateFormat);
      }
      break;
    case 'Cascader':
      {
        const flatOptions = flatCascaderOptions(options);
        result = findLabels(value, flatOptions).join('-') || '-';
      }
      break;
    case 'ListPicker':
    case 'Picker': {
      // picker 的value 是一个数组,类似[2],['3']这样的数据，导致findLabels方法无法正确处理
      // 修复：当value是数组时，直接传入findLabels函数，而不是包装成新数组
      if (Array.isArray(value) && value.length > 0) {
        result = findLabels(value, options).join('-') || value.join('-') || '-';
      } else {
        result = findLabels([value], options)[0] || value || '-';
      }
      break;
    }
    default:
      result = value;
  }

  return result || '-';
};

const Table = (props: any) => {
  const {
    schema,
    value = [],
    readOnly,
    setVisible,
    handleAdd,
    handleEdit,
  } = props;
  const [tableValue, setTableValue] = useState(value);
  const [fullScreen, setFullScreen] = useState(false);
  const { items = {} } = schema;

  useEffect(() => {
    if (value && Array.isArray(value) && value.length > 0) {
      // 从schema中获取值对应的label显示
      const properties = items.properties || {};

      // 转换数据，将原始值转换为显示值
      const transformedData = value.map((item: any) => {
        const transformedItem: any = { ...item };

        // 遍历所有属性，根据schema定义转换值
        Object.keys(properties).forEach((key) => {
          const itemSchema = properties[key];
          const rawValue = item[key];
          transformedItem[key] = getValueByWidgetType(rawValue, itemSchema);
        });

        return transformedItem;
      });

      setTableValue(transformedData);
    } else {
      setTableValue([]);
    }
  }, [value, items.properties]);

  // 获取表格列定义
  const getColumns = () => {
    // 默认从items中提取列
    const cols: any[] = [];
    const properties = items.properties || {};
    Object.keys(properties).forEach((key) => {
      const itemSchema = properties[key];
      cols.push({
        title: itemSchema.title || key,
        dataIndex: key,
        key: key,
      });
    });
    return cols;
  };

  const tableColumns = getColumns();

  const renderTable = () => {
    return (
      <div className="frm-table">
        <div className="frm-table-container">
          <div className="frm-table-wrapper">
            <div className="frm-table-body-wrapper">
              <table className="frm-table-element">
                <thead>
                  <tr>
                    <th
                      className="frm-table-element-action"
                      title="序号"
                      style={{ minWidth: 30 }}
                    >
                      序号
                    </th>
                    {tableColumns.map((col: any) => (
                      <th key={col.key} title={col.title}>
                        {col.title}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {tableValue && tableValue.length > 0 ? (
                    tableValue.map((record: any, index: number) => (
                      <tr
                        key={index}
                        className="frm-table-row-clickable"
                        onClick={() => {
                          if (!fullScreen && handleEdit) {
                            handleEdit(index);
                          }
                        }}
                      >
                        <td
                          key={index}
                          style={{ minWidth: 30, textAlign: 'center' }}
                        >
                          {index + 1}
                        </td>
                        {tableColumns.map((col: any) => (
                          <td key={col.key}>
                            {record[col.dataIndex] !== undefined
                              ? String(record[col.dataIndex])
                              : '-'}
                          </td>
                        ))}
                      </tr>
                    ))
                  ) : (
                    <tr>
                      <td
                        colSpan={tableColumns.length + 1}
                        style={{ textAlign: 'left' }}
                      >
                        暂无数据
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
        {!fullScreen ? (
          <div style={{ height: '100%', width: '100%', padding: 10 }}>
            {!readOnly && (
              <Button
                color="primary"
                block
                size="small"
                onClick={() => handleAdd && handleAdd(value.length)}
                fill="none"
              >
                <AddCircleOutline /> 添加
              </Button>
            )}

            {readOnly && value.length > 0 && (
              <Button
                color="primary"
                block
                size="small"
                onClick={() => setVisible(true)}
                fill="none"
              >
                <EyeOutline /> 查看详情
              </Button>
            )}
          </div>
        ) : null}
      </div>
    );
  };

  return (
    <>
      {!fullScreen ? (
        <LayoutCard
          title={schema.title}
          extra={
            <div
              onClick={() => {
                setFullScreen(true);
              }}
            >
              <ArrowsAltOutline style={{ transform: 'scaleX(-1)' }} />
            </div>
          }
        >
          {renderTable()}
        </LayoutCard>
      ) : (
        <div className="frm-table-fullscreen">
          <div className="frm-table-fullscreen-header">
            <div className="frm-table-fullscreen-title">{schema.title}</div>
            <div
              onClick={() => {
                setFullScreen(false);
              }}
            >
              <ShrinkOutline style={{ transform: 'scaleX(-1)' }} />
            </div>
          </div>
          <div className="frm-table-fullscreen-content">{renderTable()}</div>
        </div>
      )}
    </>
  );
};

export default Table;
